package com.zjuh.qss.biz.bo.impl;

import java.io.IOException;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import wint.lang.utils.CollectionUtil;
import wint.lang.utils.StringUtil;

import com.taobao.api.domain.TradeRate;
import com.zjuh.qss.biz.bo.PagedResult;
import com.zjuh.qss.biz.bo.TradeRateBO;
import com.zjuh.qss.common.http.ClientConnector;
import com.zjuh.qss.common.http.ClientResponse;
import com.zjuh.qss.common.http.JDKClientConnector;

public class TradeRateBOImpl implements TradeRateBO {
	
	private static final Logger log = LoggerFactory.getLogger(TradeRateBOImpl.class);

	private ClientConnector clientConnector = new JDKClientConnector();
	
	public PagedResult<TradeRate> searchTraderatesBak(long userId, long auctionId, int page) {
		String url = "http://rate.taobao.com/feedRateList.htm?userNumId="+userId
		+"&auctionNumId="+auctionId
		+"&currentPageNum="+page
		+"&rateType=&orderType=sort_weight&showContent=1&attribute=&callback=jsonp_reviews_list";
		String content = doGetForString(url);
		PagedResult<TradeRate> pagedResult = new PagedResult<TradeRate>();
		try {
			content = content.trim();
			content = StringUtil.getFirstAfter(content, "jsonp_reviews_list(");
			content = StringUtil.getLastBefore(content, ")");
			
			JSONObject json = new JSONObject(content);
			
			int maxPage = json.getInt("maxPage");
			//pagedResult.setMaxPage(maxPage);
			pagedResult.setMaxCount(maxPage);
			List<TradeRate> rates = CollectionUtil.newArrayList();
			
			if (!json.has("comments")) {
				pagedResult.setResults(rates);
				return pagedResult;
			}
			Object o = json.get("comments");
			if (!(o instanceof JSONArray)) {
				return pagedResult;
			}
			JSONArray array = json.getJSONArray("comments");
			for (int i = 0, len = array.length(); i < len ; ++i) {
				JSONObject rateJson = array.getJSONObject(i);
				TradeRate tradeRate = new TradeRate();
				String rateContent = rateJson.getString("content");
				int rate = rateJson.getInt("rate");
				if (rate != 1) {
					continue;
				}
				tradeRate.setContent(rateContent);
				rates.add(tradeRate);
			}
			pagedResult.setResults(rates);
		} catch (Exception e) {
			log.error("searchTraderates error", e);
		}
		return pagedResult;
	}
	
	public PagedResult<TradeRate> searchTraderates(long auctionId, int page) {
		String url = "http://rate.tmall.com/list_detail_rate.htm?itemId="+ auctionId +"&order=0&currentPage=" + page;
		String content = doGetForString(url);
		PagedResult<TradeRate> pagedResult = new PagedResult<TradeRate>();
		try {
			content = content.trim();
			content = StringUtil.getFirstAfter(content, ":");
			content = StringUtil.trimToEmpty(content);
			if (StringUtil.isEmpty(content)) {
				return pagedResult;
			}
			JSONObject json = new JSONObject(content);
			
			JSONObject paginator = json.getJSONObject("paginator");
			int items = paginator.getInt("items");
			pagedResult.setMaxCount(items);
			
			int lastPage = paginator.getInt("lastPage");
			pagedResult.setLastPage(lastPage);
			
			if (page >  lastPage) {
				return pagedResult;
			}
			
			JSONArray array = json.getJSONArray("rateList");
			List<TradeRate> rates = CollectionUtil.newArrayList();
			for (int i = 0, len = array.length(); i < len ; ++i) {
				JSONObject rateJson = array.getJSONObject(i);
				String stringDsr = rateJson.getString("dsr");
				double dsr = 0.0;
				if (StringUtil.isEmpty(stringDsr)) {
					dsr = 4.0;
				} else {
					try {
						dsr = Double.parseDouble(stringDsr);
					} catch (Exception e) {
						dsr = 0.0;
					}
				}
				if (dsr < 4.0) {
					continue;
				}
				String rateContent = rateJson.getString("rateContent");
				TradeRate tradeRate = new TradeRate();
				tradeRate.setContent(rateContent);
				rates.add(tradeRate);
			}
			pagedResult.setResults(rates);
		} catch (Exception e) {
			log.error("searchTraderates error", e);
		}
		return pagedResult;
	}
	
	private String doGetForString(String url) {
		try {
			ClientResponse clientResponse = clientConnector.request(url, false, null, null, null, null);
			byte[] data = clientResponse.getData();
			String charset = JDKClientConnector.getCharset(clientResponse.getHeaders());
			if (StringUtil.isEmpty(charset)) {
				charset = "utf-8";
			}
			return new String(data, charset);
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}
	
}
